package com.hengtongxing.hejiayun.homepage;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.BaseActivity;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.BaseResponseBean;
import com.hengtongxing.hejiayun.bean.ImageBean;
import com.hengtongxing.hejiayun.bean.MyHouseListBean;
import com.hengtongxing.hejiayun.dialog.MyHouseDialog;
import com.hengtongxing.hejiayun.homepage.model.HomePageModelImpl;
import com.hengtongxing.hejiayun.homepage.model.IHomePageModel;
import com.hengtongxing.hejiayun.mine.model.MineModelImpl;
import com.hengtongxing.hejiayun.shop.adapter.Adapter_PictureSelector;
import com.hengtongxing.hejiayun.utils.Base64BitmapUtil;
import com.hengtongxing.hejiayun.utils.GlideEngine;
import com.hengtongxing.hejiayun.utils.PermissionsManager;
import com.hengtongxing.hejiayun.utils.ToastUtil;
import com.hengtongxing.hejiayun.widget.AppTitleBar;
import com.hengtongxing.hejiayun.widget.FullyGridLayoutManager;
import com.hengtongxing.hejiayun.widget.ViewLoading;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
//import com.luck.picture.lib.widget.MyViewPageHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RepairsServiceActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.ll_select_house)
    LinearLayout llSelectHouse;
    @BindView(R.id.edit_info)
    EditText editInfo;
    @BindView(R.id.ll_select_time)
    LinearLayout llSelectTime;
    @BindView(R.id.tv_house)
    TextView tvHouse;
    @BindView(R.id.tv_select_time)
    TextView tvSelectTime;

    private Adapter_PictureSelector adapter;
    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private IHomePageModel homePageModel;
    private List<String> imgList = new ArrayList<>();
    private ArrayList<String> optionsItems = new ArrayList<>();
    private String hose_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repairs_service);
        ButterKnife.bind(this);
        initView();
        requestMyHouse();
    }

    public void initView() {
        homePageModel = new HomePageModelImpl();
        titleBar.setRightClickListener(() -> {
            showActivity(RepairsListActivity.class);
        });
        permissionsManager = new PermissionsManager(this);
        FullyGridLayoutManager fullyGridLayoutManager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(fullyGridLayoutManager);

        adapter = new Adapter_PictureSelector(this);
        adapter.setImgList(imgList);
        recyclerView.setAdapter(adapter);
        adapter.setOnAddPicClickListener(this::showPictureSelectorDialog);
        adapter.setOnItemClickListener(this::handlerAdapterItemClick);
        optionsItems.add("尽快上门");
        optionsItems.add("一天之内");
        optionsItems.add("一周之内");
    }

    public void requestMyHouse() {
        new MineModelImpl().requestMyHouse(new DataCallBack<MyHouseListBean>() {
            @Override
            public void onSuccessful(MyHouseListBean bean) {
                if (bean.getData().size() > 0) {
                    for (MyHouseListBean.DataBean dataBean : bean.getData()) {
                        if (dataBean.getIs_def() == 1) {
                            String address = dataBean.getComm_name() + dataBean.getBuilding() + dataBean.getUnit_name() + dataBean.getFloor() + dataBean.getHose_number();
                            tvHouse.setText(address);
                            hose_id = dataBean.getId() + "";
                            return;
                        }
                    }
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void showGsInfo() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvSelectTime.setText(optionsItems.get(options1));
            }
        }).setTitleText("")
                .setTitleSize(16)
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(16)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(16)
                .setLineSpacingMultiplier(2)
                .isDialog(true)
                .build();


        pvOptions.setPicker(optionsItems);


        Dialog mDialog = pvOptions.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvOptions.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvOptions.show();

    }

    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(this, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    private void handlerAdapterItemClick(int position, View v) {

//        List<LocalMedia> selectList = adapter.getMediaList();

//        if (selectList != null && selectList.size() > 0) {
//            PictureSelector.create(this).externalPicturePreview(position, selectList, 0);
//        }
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }


    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }


    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(mActivity)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(new ArrayList<>())//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(mActivity)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(new ArrayList<>())//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }
    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            if (openType == 0) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else if (openType == 1) {
                openCamera();
                cancelPictureDialog();
            }
        }
    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                if (isDestroy()) {
                    return;
                }
                List<LocalMedia> list = new ArrayList<>();
                LocalMedia localMedia = new LocalMedia();
                localMedia.setPath(bean.getData().getUrl());
                list.add(localMedia);
                adapter.addMediaList(list);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @OnClick({R.id.ll_select_house, R.id.ll_select_time, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_house:
                MyHouseDialog dialog = MyHouseDialog.newInstance();
                dialog.show(getSupportFragmentManager(), "dialog");
                dialog.setOnCallBackListener((name, id) -> {
                    tvHouse.setText(name);
                    hose_id = id;
                });
                break;
            case R.id.ll_select_time:
                showGsInfo();
                break;
            case R.id.tv_commit:
                if (TextUtils.isEmpty(hose_id)) {
                    ToastUtil.showShort("请选择房屋");
                    return;
                }
                String info = editInfo.getText().toString();
                String visit_time = tvSelectTime.getText().toString();
                if (TextUtils.isEmpty(info)) {
                    ToastUtil.showShort("请输入问题详情");
                    return;
                }
                requestHousesRepairAdd(info, visit_time);
                break;
        }
    }

    public void requestHousesRepairAdd(String info, String visit_time) {
        ViewLoading.showProgress(mActivity, "提交中......");
        homePageModel.requestHousesRepairAdd(hose_id, info, imgList, visit_time, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("提交成功");
                showActivity(RepairsListActivity.class);
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }
}
